// import router,{ operationPage } from "@router/index"
import store from "./store"
import { param2Obj } from "@utils/index"
import router, {
  operationPage,
  notFound,
  registerPage,
  waitPage
} from "@router/index"

function initPage() {
  return Promise.resolve().then((/* res */) => {
    /* const {
      data: { state }
    } = res */
    const query = param2Obj(window.location.search) || {}
    const state = +(query.state || "1")
    // const state = 3
    store.dispatch("pageState/setState", state)

    return addRoutes(state)
  })
}
function addRoutes(state) {
  store.dispatch("pageState/setLoad", true)

  let page = ""
  let routes = []
  if (state === 1) {
    page = "/register"
    routes = [...registerPage, ...waitPage]
  } else if (state === 2) {
    page = "/wait"
    routes = waitPage
  } else if (state === 3) {
    page = "/home"
    routes = operationPage
  }

  routes.forEach((route) => {
    router.addRoute("root", route)
  })
  addView(routes)

  router.addRoute(notFound)
  return page
}

router.beforeEach((to, from, next) => {
  let isLoad = store.getters["pageState/isLoad"]
  let state = store.getters["pageState/state"]

  if (state === null) {
    initPage()
      .then((page) => {
        next(/* { path: "/", replace: true } */)
        return page
      })
      .then((page) => {
        page && router.push(page)
      })
  } else if (!isLoad) {
    const page = addRoutes(state)
    // if (from.path !== page) {
    next(page)
    // }
  } else {
    next()
  }
})

function addView(routes = []) {
  routes.forEach((route) => {
    store.dispatch("tagsView/addView", route)
    if (route.children) {
      addView(route.children)
    }
  })
}
/* router.beforeEach((to, from, next) => { 
  if (!isLoad) { 
    addView(operationPage)
    store.dispatch('pageState/setLoad', true);
  }

  next();
})
 */
router.afterEach(() => {
  // console.log("afterEach")
})
